//
//  XLProblemVC.m
//  industry
//
//  Created by xl on 2021/1/8.
//  Copyright © 2021 Haier. All rights reserved.
//

#import "XLProblemVC.h"
#import "XLProblemHeaderView.h"
#import "WKDelegateVC.h"

@interface XLProblemVC ()<DTNavigationBarAppearanceProtocol, WKDelegate, WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) XLProblemHeaderView *headerView;
@property (nonatomic, strong) XLView *webBgView;
@property (nonatomic, strong) WKWebView *webView;

@end

@implementation XLProblemVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self buildView];
}

- (void)buildView {
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.webBgView];
    [_webBgView addSubview:self.webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webBgView).offset(28);
        make.left.bottom.right.equalTo(self.webBgView);
    }];
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", XLServerHttpDomain, XLCommonProblemUrl]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10]];

}

#pragma mark - UIButton
- (void)clickBack {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - DTNavigationBarAppearanceProtocol
- (BOOL)autohideNavigationBar {
    return YES;
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(nonnull NSError *)error {
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
        if (response.statusCode >= 400 && response.statusCode < 510) {
            //不允许跳转
            decisionHandler(WKNavigationResponsePolicyCancel);
            return;
        }
    }
    XLLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    XLLog(@"URL:%@",navigationAction.request.URL.absoluteString);
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    XLLog(@"scheme:%@",scheme);
    if ([scheme isEqualToString:@"tel"]) {
        //取消WKWebView 打电话请求 不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
        
        //用openURL 这个API打电话
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSMutableString *str= [[NSMutableString alloc] initWithFormat:@"tel:%@",resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
    else{
        //允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}

// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}

// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    XLLog(@"i accept message:: %@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
//解析js内容
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"xlapp"]) {
        NSDictionary *dic = message.body;
        XLLog(@"OK:::%@",dic);

    }
    XLLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}

#pragma mark - Private
- (void)clearCache {
    //清除缓存
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
    }];
}

#pragma mark - Setter/getter
- (XLProblemHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XLProblemHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 262/375.0)];
        [_headerView.backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headerView;
}

- (XLView *)webBgView {
    if (!_webBgView) {
        _webBgView = [[XLView alloc] initWithFrame:CGRectMake(0, 100 + STATUSBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 100 - STATUSBAR_HEIGHT)];
        _webBgView.backgroundColor = [UIColor colorWithHex:0xF7F8FC];
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 100 - STATUSBAR_HEIGHT);
        UIBezierPath *cornerRaduisPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:UIRectCornerTopLeft cornerRadii:CGSizeMake(50, 50)];
        CAShapeLayer *cornerRadiusLayer = [[CAShapeLayer alloc] init];
        cornerRadiusLayer.frame = frame;
        cornerRadiusLayer.path = cornerRaduisPath.CGPath;
        _webBgView.layer.mask = cornerRadiusLayer;
    }
    return _webBgView;
}

- (WKWebView *)webView {
    if (!_webView) {
        //配置环境
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *usercontentVC = [[WKUserContentController alloc] init];
        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WKDelegateVC *delegateVC = [[WKDelegateVC alloc] init];
        delegateVC.delegate = self;
        [usercontentVC addScriptMessageHandler:delegateVC name:@"xlapp"];//注册一个name为xlapp的js方法
        configuration.userContentController = usercontentVC;
        // 默认认为YES
        configuration.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;

        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
        _webView.scrollView.scrollEnabled = YES;
        _webView.scrollView.backgroundColor = [UIColor colorWithHex:0xF7F8FC];
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
    }
    return _webView;
}
@end
